package com.hzjh.base.web.util

import android.content.Context
import android.graphics.Rect
import android.view.View
import android.widget.FrameLayout

/**
 * 全屏模式的情况，adjustPan跟adjustResize都会失效
 * Android系统本身的一个BUG
 * 该类解决此问题
 */
class AndroidBug5497Workaround(content: FrameLayout, private val context:Context) {
    // For more information, see https://issuetracker.google.com/issues/36911528
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.

    // For more information, see https://issuetracker.google.com/issues/36911528
    // To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
    companion object{
        fun assistActivity(content: FrameLayout,context: Context) {
            AndroidBug5497Workaround(content,context)
        }
    }

    private var mChildOfContent: View
    private var usableHeightPrevious = 0
    private var frameLayoutParams: FrameLayout.LayoutParams? = null

    init {
        mChildOfContent = content.getChildAt(0)
        mChildOfContent.viewTreeObserver
            .addOnGlobalLayoutListener { possiblyResizeChildOfContent() }
        frameLayoutParams = mChildOfContent.layoutParams as FrameLayout.LayoutParams
    }

    private fun possiblyResizeChildOfContent() {
        val usableHeightNow = computeUsableHeight()
        if (usableHeightNow != usableHeightPrevious) {
            val usableHeightSansKeyboard: Int = mChildOfContent.rootView.height
            val heightDifference = usableHeightSansKeyboard - usableHeightNow
            if (heightDifference > usableHeightSansKeyboard / 4) {
                // keyboard probably just became visible
                frameLayoutParams?.height = usableHeightSansKeyboard - heightDifference + WebUtil.px2dip(WebUtil.getStatusBarHeight(),context).toInt()

            } else {
                // keyboard probably just became hidden
                frameLayoutParams?.height = FrameLayout.LayoutParams.MATCH_PARENT
            }
            mChildOfContent.requestLayout()
            usableHeightPrevious = usableHeightNow
        }
    }

    private fun computeUsableHeight(): Int {
        val r = Rect()
        mChildOfContent.getWindowVisibleDisplayFrame(r)
        return r.bottom - r.top
    }
}